import { Checkbox, Dropdown } from 'antd';
import { memo, useMemo, useState } from 'react';
import { Layout, useRefCallback } from '../../../util';
import { OrgTree as Tree } from '../../org-tree';

/**
 * 组织树
 * @param props
 * @constructor
 */
function OrgTree(props) {
  const params = useMemo(() => {
    return { containDept: false, dataAccessAuth: true, ...props.params };
  }, [props.params]);
  return <Tree /* defaultSelectedFirstNode */ {...props} params={params} />;
}

/**
 * tree
 * @param props
 * @returns
 */
function ProjectEngineeringTree(props) {
  const { treeProps, getTable } = props;
  const [treeSelectedKeys, setTreeSelectedKeys] = useState<string[]>([]);

  // 点击包含下级
  const onChangeIfNeedSub = useRefCallback((value) => {
    getTable().setExtraParam({ containLowOrgUser: value });
  });

  // 受控select
  const onControlledSelect = useRefCallback((keys, { selectedNodes }) => {
    const treeNodes = selectedNodes.filter((xt) => !treeSelectedKeys.includes(xt.key)) || [];
    const treeKeys = keys.filter((xt) => !treeSelectedKeys.includes(xt)) || [];
    getTable().setExtraParam({ treeNodes });
    setTreeSelectedKeys(treeKeys);
  });

  // <包含下级> 功能
  const handleFilter = (DefaultCom) => {
    return (
      <>
        {DefaultCom}
        <Checkbox
          style={{ marginBottom: 5 }}
          onChange={(e) => {
            onChangeIfNeedSub(e.target.checked);
          }}
        >
          包含下级
        </Checkbox>
      </>
    );
  };

  return (
    <Layout.Flex direction="row" style={{ height: '100%', border: '1px solid var(--border-color-split, #f0f0f0)' }}>
      <OrgTree
        {...treeProps}
        showFilter={handleFilter}
        selectedKeys={treeSelectedKeys}
        onSelect={onControlledSelect}
        titleRender={({ title, key }) => (
          <Dropdown
            disabled={!treeSelectedKeys.includes(key)}
            trigger={['contextMenu']}
            menu={{ items: [{ key: 'cancle', label: '取消选中' }] }}
            placement="top"
          >
            <span>{title}</span>
          </Dropdown>
        )}
      />
    </Layout.Flex>
  );
}

export default memo(ProjectEngineeringTree);
